#include "Sphere.h"


Sphere::Sphere(Vector3d position,double radius) : RenderObject(position),rad(radius)
{

}


Sphere::~Sphere(void)
{
}

TraceResult Sphere::collision(const Ray &ray)
{
	Vector3d no(0,0,0);

	if(Vector3d::distance(ray.position,position) <= rad)
		return TraceResult::empty;

	Vector3d rayToSphereCenter = position - ray.position;

	double lengthRTSC2 = rayToSphereCenter.dot( rayToSphereCenter );
	double closestApproach = rayToSphereCenter.dot( ray.direction );
	if ( closestApproach < 0 ) {
		return TraceResult::empty;
	}

	double halfCord2 = (rad * rad) - lengthRTSC2 + (closestApproach * closestApproach);

	if ( halfCord2 < 0 ) 
	{
		return TraceResult::empty;
	}

	double dist = (closestApproach - sqrt( halfCord2 ));

	Vector3d q = static_cast<Vector3d>(ray.direction) * dist;
	Vector3d hit = static_cast<Vector3d>(ray.position) + q;

	Vector3d normal = hit - position;
	normal.Normalize();

	return TraceResult( true ,dist,hit ,normal,this);
}
